import { getGoodsList } from "@/api/home/goods";
import { useRouterNavigation } from "@/router/utils";
import { useDictStoreHook } from "@/store/modules/dict";
import { getDictLabel } from "@/utils/dict";
import { message } from "@/utils/message";
import type { PaginationProps } from "@pureadmin/table";
import dayjs from "dayjs";
import { onMounted, reactive, ref, toRaw, watch } from "vue";

export function useHome() {
  const treeRef = ref();
  const goodsType = ref(1);
  const typeList = ref([]);
  const form = reactive({
    goodsType: 1,
    searchContent: "",
    pageNum: 1,
    pageSize: 20
  });
  const curRow = ref();
  const dataList = ref([]);
  const treeIds = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const isLinkage = ref(false);
  const treeSearchValue = ref();
  const isExpandAll = ref(false);
  const isSelectAll = ref(false);
  const treeProps = {
    value: "id",
    label: "title",
    children: "children"
  };
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "角色名称",
      prop: "name"
    },
    {
      label: "角色标识",
      prop: "roleCode"
    },
    {
      label: "创建人",
      prop: "createUserName"
    },
    {
      label: "创建时间",
      prop: "gmtCreate",
      minWidth: 160,
      formatter: ({ gmtCreate }) => dayjs(gmtCreate).format("YYYY-MM-DD HH:mm")
    },
    {
      label: "操作",
      fixed: "right",
      width: 210,
      slot: "operation"
    }
  ];

  // 查看商品详情
  const { push } = useRouterNavigation();
  const showGoodsDetail = row => {
    push({
      path: "/home/goods/detail",
      query: { id: row.id }
    });
  };

  const handleDelete = () => {
    message("删除成功", { type: "success" });
    onSearch();
  };

  function handleSizeChange(val: number) {
    form.pageNum = 1;
    form.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    form.pageNum = val;
    onSearch();
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  async function onSearch() {
    loading.value = true;
    form.goodsType = goodsType.value;
    const { data } = await getGoodsList(toRaw(form));
    dataList.value = data.records || [];
    pagination.total = data.total;
    pagination.pageSize = data.pageSize;
    pagination.currentPage = data.currentPage;
    setTimeout(() => {
      loading.value = false;
    }, 200);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  /** 高亮当前权限选中行 */
  function rowStyle({ row: { id } }) {
    return {
      cursor: "pointer",
      background: id === curRow.value?.id ? "var(--el-fill-color-light)" : ""
    };
  }

  /** 菜单权限-保存 */
  function handleSave() {
    const { id, name } = curRow.value;
    // 根据用户 id 调用实际项目中菜单权限修改接口
    console.log(id, treeRef.value.getCheckedKeys());
    message(`角色名称为${name}的菜单权限修改成功`, {
      type: "success"
    });
  }

  /** 数据权限 可自行开发 */
  // function handleDatabase() {}

  const onQueryChanged = (query: string) => {
    treeRef.value!.filter(query);
  };

  const filterMethod = (query: string, node) => {
    return node.title!.includes(query);
  };

  onMounted(async () => {
    const params = {
      pageNum: 1,
      pageSize: 999
    };
    const { data } = await useDictStoreHook().getDictlist(params);
    typeList.value = getDictLabel(data.records, "PRODUCT_TYPE");
    onSearch();
  });

  watch(isExpandAll, val => {
    val
      ? treeRef.value.setExpandedKeys(treeIds.value)
      : treeRef.value.setExpandedKeys([]);
  });

  watch(isSelectAll, val => {
    val
      ? treeRef.value.setCheckedKeys(treeIds.value)
      : treeRef.value.setCheckedKeys([]);
  });

  watch(goodsType, () => {
    form.searchContent = "";
    form.pageNum = 1;
    form.pageSize = 20;
    onSearch();
  });

  return {
    form,
    typeList,
    isShow,
    curRow,
    loading,
    columns,
    rowStyle,
    dataList,
    treeProps,
    isLinkage,
    pagination,
    isExpandAll,
    isSelectAll,
    treeSearchValue,
    goodsType,
    onSearch,
    resetForm,
    handleSave,
    handleDelete,
    filterMethod,
    onQueryChanged,
    // handleDatabase,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    showGoodsDetail
  };
}
